package com.ydsungan.worldbook.utils;

import com.ydsungan.worldbook.pojo.Book;
import com.ydsungan.worldbook.pojo.BookSearch;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

public class HttpClientUtil {

    private static String suggestUrl =  "https://book.douban.com/j/subject_suggest";
    private static CloseableHttpClient httpClient;


    public static Book parseApi(String keyWords) throws URISyntaxException {
        httpClient =  HttpClients.createDefault();
        URIBuilder uriBuilder = new URIBuilder(suggestUrl);
        uriBuilder.setParameter("q",keyWords);

        HttpGet httpGet = new HttpGet(uriBuilder.build());
        System.out.println(httpGet);
        CloseableHttpResponse response = null;
        Book book = null;
        try {
            response = httpClient.execute(httpGet);

            if(response.getStatusLine().getStatusCode() == 200){
                String content = EntityUtils.toString(response.getEntity());

                List list = JSONUtils.jsonToList(content, Class.forName("com.ydsungan.worldbook.pojo.BookSearch"));
                if(list.size() > 0){
                    BookSearch result = (BookSearch) list.get(0);
                    book = parseWebPage(result.getUrl());
                    if(book != null){
                        book.setAuthor(result.getAuthor_name());
                        book.setCoverUrl(result.getPic());
                        book.setBookName(result.getTitle());
                    }else{
                        throw new RuntimeException("html解析失败");
                    }
                }else{
                    System.out.println("content:" + content);
                    throw new RuntimeException("Json串解析失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return book;
        }
    }

    public static Book parseWebPage(String url){

        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);

            if(response.getStatusLine().getStatusCode() == 200){
                String content = EntityUtils.toString(response.getEntity());


                Document doc = Jsoup.parse(content);
                String info = doc.select(".blockquote-list li:eq(0)").first().text();

                String detail = doc.select("#info").first().text();
                //豆瓣评分
                float score =  Float.parseFloat(doc.select(".rating_num").first().text().trim());

                String ISBN = detail.substring(detail.indexOf("ISBN")+5).trim();
                int pageNum = Integer.parseInt(detail.substring(detail.indexOf("页数")+3,detail.indexOf("定价")).trim());

                Elements tags =  doc.select("#db-tags-section a");
                String type = "[";
                for (Element tag: tags) {
                    type +=  tag.text().trim() + ",";
                }
                String bookType = type.substring(0, type.length()-1) + "]";

                Book book = new Book();
                book.setContentIntroduction(info.substring(0, info.indexOf("(查看原文)")));
                book.setScore(score);
                book.setISBN(ISBN);
                book.setPageNum(pageNum);
                book.setBookType(bookType);
                return book;

            }else{

                throw new RuntimeException("请求豆瓣失败..");
            }
        } catch (Exception e) {

            e.printStackTrace();
            return null;
        }finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
